package com.cheetah.handler;

/**
 * @Author Administrator
 * @Date 2019/7/31
 * @Version V1.0
 * @Description:
 **/

import com.cheetah.protocol.Heartbeat;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class HeartBeatClientHandler extends SimpleChannelInboundHandler<Heartbeat> {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) {
                ctx.channel().writeAndFlush(Heartbeat.builder()
                        .cmd("ping")
                        .build());
                log.info("client send ping cammand! {}",new Date());
            }
        }
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Heartbeat msg) throws Exception {
        log.info("client receive {}",msg.getCmd());
    }
}
